// 忘记密码
import React from 'react';
import {
  Image, StyleSheet, View, TextInput, ScrollView, ImageBackground
} from 'react-native';
import { Button, WhiteSpace } from 'antd-mobile-rn';
import { NavigationActions } from 'react-navigation';
import VerificationCode from '../components/VerificationCode';
import BaseView from './BaseView';
import { sendMsg, updatePassword } from '../model/user';

export default class ForgetPassword extends BaseView {
  constructor() {
    super();
    this.state = {
      ...this.BaseState, // 继承基础state
      phone: '',
      yzm: '',
      time: 60,
      psw: '',
      newpsw: ''
    };
    this.onStart = this.onStart.bind(this);
  }

  // 生命周期render前
  componentWillMount() {
    const { navigation } = this.props;
    navigation.setParams({ goback: this.goback.bind(this) });
  }

  componentDidMount() {
    // 设置头部
    super.componentDidMount();
    this.props.navigation.setParams({
      title: '忘记密码',
      backgroundColor: '#fff',
      textColor: '#000'
    });
    super.setState({
      loading: true
    });
  }

  async onStart() {
    const { phone } = this.state;
    if (this.checkPhone(phone)) {
      // alert('验证通过, 稍后请查收');
      await sendMsg({
        mobile: phone
      });
      return true;
    }
    alert('手机号不正确, 修改后再试');
    return false;
  }

  goback() {
    const { navigation } = this.props;
    const backAction = NavigationActions.back();
    navigation.dispatch(backAction);
  }

  toMainPage() {
    const { navigation } = this.props;

    const navigateAction = NavigationActions.navigate({
      routeName: 'Main',
      params: {}
    });
    navigation.dispatch(navigateAction);
  }

  async submit(phone, yzm, psw, newpsw) {
    if (!this.checkPhone(phone)) {
      alert('手机号不正确');
      return false;
    }
    if (!yzm) {
      alert('验证码不能为空');
      return false;
    }
    if (psw.length < 8) {
      alert('请输入8-18位字母+数字组合密码');
      return false;
    }
    if (psw.length > 18) {
      alert('请输入8-18位字母+数字组合密码');
      return false;
    }
    if (newpsw !== psw) {
      alert('两次密码输入不一致，请重新输入');
      return false;
    }

    await updatePassword({
      passwordObject: {
        mobile: phone,
        password: psw,
        verificationCode: yzm
      }
    });
    alert('密码修改成功！');

    this.toMainPage();
    return false;
    // 提交保存
  }

  chkNumber(obj) {
    const reg = /^[0-9]+$/;
    if (!reg.test(obj)) {
      obj = obj.substr(0, obj.length - 1);
    }
    return obj;
  }

  checkPhone(phone) {
    return phone.length === 11;
  }

  chkPsw(obj) {
    const reg = /^[0-9a-zA-Z]+$/;
    if (!reg.test(obj)) {
      obj = obj.substr(0, obj.length - 1);
    }
    return obj;
  }

  renderPage() {
    const {
      phone, yzm, time, psw, newpsw
    } = this.state;
    return (
      <View style={forgetPassword.container}>
        <ImageBackground
          style={forgetPassword.backgroundImage}
          source={{
            uri:
              'https://mxb-bucket.oss-cn-beijing.aliyuncs.com/_app/%E4%BF%AE%E6%94%B9%E5%AF%86%E7%A0%81%E8%83%8C%E6%99%AF%E5%9B%BE.jpg'
          }}
          resizeMode="cover"
        >
          <ScrollView
            contentContainerStyle={forgetPassword.wrap}
            automaticallyAdjustContentInsets={false}
            showsHorizontalScrollIndicator={false}
            showsVerticalScrollIndicator={false}
          >
            <View style={forgetPassword.content}>
              <Image source={require('../../img/logo.png')} style={forgetPassword.logo} />
            </View>
            <View style={forgetPassword.row}>
              <View style={forgetPassword.inputWrap}>
                <TextInput
                  style={forgetPassword.input}
                  placeholder="请输入手机号"
                  underlineColorAndroid="transparent"
                  value={phone}
                  onChangeText={(text) => {
                    this.setState({ phone: this.chkNumber(text) });
                  }}
                />
                <WhiteSpace />
                <View
                  style={{
                    width: SCALE(576),
                    height: SCALE(76),
                    position: 'relative'
                  }}
                >
                  <TextInput
                    style={forgetPassword.input}
                    keyboardType="number-pad"
                    placeholder="请输入验证码"
                    underlineColorAndroid="transparent"
                    value={yzm}
                    onChangeText={(text) => {
                      this.setState({ yzm: this.chkNumber(text) });
                    }}
                  />
                  <View style={forgetPassword.yzm}>
                    <VerificationCode time={time} onStart={this.onStart} />
                  </View>
                </View>
                <WhiteSpace />
                <TextInput
                  style={forgetPassword.input}
                  placeholder="请输入新密码"
                  underlineColorAndroid="transparent"
                  secureTextEntry
                  value={psw}
                  onChangeText={(text) => {
                    this.setState({ psw: this.chkPsw(text) });
                  }}
                />
                <WhiteSpace />
                <TextInput
                  style={forgetPassword.input}
                  placeholder="请重新输入新密码"
                  underlineColorAndroid="transparent"
                  secureTextEntry
                  value={newpsw}
                  onChangeText={(text) => {
                    this.setState({ newpsw: this.chkPsw(text) });
                  }}
                />
              </View>
            </View>
            <Button
              type="primary"
              style={forgetPassword.btnWrap}
              onClick={() => { this.submit(phone, yzm, psw, newpsw); }}
            >确 定
            </Button>
          </ScrollView>
        </ImageBackground>
      </View>
    );
  }
}

const forgetPassword = StyleSheet.create({
  container: {
    flex: 1
  },
  backgroundImage: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    width: null,
    height: null,
    // 不加这句，就是按照屏幕高度自适应
    // 加上这几，就是按照屏幕自适应
    // resizeMode:Image.resizeMode.contain,
    // 祛除内部元素的白色背景
    backgroundColor: 'rgba(0,0,0,0)'
  },
  wrap: {
    flex: 1,
    alignItems: 'center',
    marginTop: SCALE(228)
  },
  content: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  logo: {
    width: SCALE(176),
    height: SCALE(50),
    marginBottom: SCALE(83)
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'center'
  },
  inputWrap: {
    width: SCALE(576)
  },
  input: {
    width: SCALE(576),
    height: SCALE(76),
    borderWidth: 1,
    borderColor: '#ccc',
    borderStyle: 'solid',
    borderRadius: 8,
    paddingRight: SCALE(30),
    paddingLeft: SCALE(30),
    backgroundColor: '#fff',
    position: 'relative'
  },
  yzm: {
    position: 'absolute',
    right: 0,
    top: 0,
    borderRadius: 4,
    height: SCALE(76),
    paddingLeft: SCALE(25),
    paddingRight: SCALE(25),
    backgroundColor: '#044e8d'
  },
  btnWrap: {
    marginTop: SCALE(86),
    width: SCALE(576),
    height: SCALE(76),
    backgroundColor: '#044e8d',
    borderWidth: 0
  }
});
